extension TimeX on DateTime {
  /// 两位补零
  String _twoDigits(int n) => n.toString().padLeft(2, '0');

  /// 转换为完整日期时间字符串，例如：`2023-01-01 00:00:00`
  String get toStr => '$year-${_twoDigits(month)}-${_twoDigits(day)} ${_twoDigits(hour)}:${_twoDigits(minute)}:${_twoDigits(second)}';

  /// 转换为年月日字符串，例如：`2023-01-01`
  String get toStrYMD => '$year-${_twoDigits(month)}-${_twoDigits(day)}';

  /// 转换为相对时间描述，例如：“5分钟前”、“2天前”
  String get toAgo {
    final now = DateTime.now();
    final diff = now.difference(this);

    if (diff.inDays >= 30) return '${diff.inDays ~/ 30}月前';
    if (diff.inDays > 0) return '${diff.inDays}天前';
    if (diff.inHours > 0) return '${diff.inHours}小时前';
    if (diff.inMinutes > 0) return '${diff.inMinutes}分钟前';
    return '刚刚';
  }
}
